//index.js
var req = require('../../interfaceImpl.js');
var config = require('../../interfaceConfig.js');
var zuodata = require("../../utils/zuodata.js");//座位的数据
var strAppCode = config.SmallApp;
var result;
var code = "";
var order = "";
var reqLockSeatSign = '';
var distanceList = [];
var xMove = "";
var yMove = "";
var order = "";
//获取应用实例
var Cinemapojo = '';
var plandate = '';
var danprice = '';
var totalprice = 0;
var showdate = '';
var ReqGetSeatMapSign = ''
const app = getApp()
var buyitem = "";
var col;
var Seat = '';
var showrow = [];
var showcol = [];
var noPaySeat = [];
var hasChooseSeat = [];
var oldDistence = '';
var newDistence = "";
var distance = "";
var distanceDiff = "";
var flag = 0;
var UserID = "";
var cancou = false;
var payandshowprice = 0
var detail = "";
var EventId = "";
var minSeatCol = "";
var LockCheck_rows = "";
var LockCheck_graphcels = "";
var minSeatCol = "";
Page({
  data: {
    enlarge: 1,

    scale: 1.5,
    hangnumTop: 65,
    hangscale: 1,
    //座位数据
    zuolist: [],//座位数据
    chkzuolist: [],
    totalprice: totalprice,
    price: 0,//票价
    // payforprice: 0,//付钱价格
    tingnum: 0,//电影厅号
    dyid: 0,//电影id
    left:0,
    dyname: '',//电影名称
    yyid: 0, //影院id
    yyname: '', //影院名称
    tian: '',//今明后天
    chkday: '',//日期
    changciid: '',//场次id
    // time: '',//开场时间
    leixing: '',//电影类型

    isnoshow: true,//是否已经结束
    showbottom: false,//显示底线

    showmodel: false,//是否显示弹窗
    animationData: '',//动画
  },

  //页面的初始化
  onLoad: function (options) {
    wx.showLoading({
      title: '座位图生成中',
    })
    console.log(options)
    detail = JSON.parse(options.detail)
    buyitem = options.buyitem;
    console.log(buyitem)
    this.setData({ payandshowprice })
    //TODO先判断是否登录
    UserID = app.globalData.cinemapojo.UserID
    hasChooseSeat = []
    Cinemapojo = JSON.parse(options.Cinemapojo);
    plandate = JSON.parse(options.plandate);
    danprice = plandate.mPriceLowest;//不确定
    showdate = options.showdate;
    EventId = options.EventId;
    console.log("+++++++cjhoose" + EventId)
    var that = this;

    that.setData({
      Cinemapojo,
      plandate,
      showdate
    })
    //座位位置部分
    //TODO 请求座位图
    var getSeatMapSign = "strAppCode=" + strAppCode + "CinemaCode=" + Cinemapojo.CinemaCode + "PlanCodeApp=" + plandate.PlanCodeApp;
    return req.GetSignStr(getSeatMapSign).then(res => {
      if (res.data.success)
        ReqGetSeatMapSign = res.data.data
    }).then(() => {
      return req.GetPlanSiteState(strAppCode, Cinemapojo.CinemaCode, plandate.PlanCodeApp, ReqGetSeatMapSign).then(res => {
        var column = 0;
        var row = 0;
        var mincol = 0;
        Seat = res.data.data;
        mincol = Seat[0].ScreenCol;
        for (let i = 0; i < Seat.length; i++) {
          if (i == Seat.length - 1) {
            column = Seat[i].ScreenCol
            row = Seat[i].ScreenRow
          }
        }
        console.log(Seat)
        result = zuodata.getXiSeat(column, row, Seat);

        //TODO 过滤空行
        var num = 0;
        var finalres = [];
        for (var i = 0; i < result.length; i++) {
          for (var j = 0; j < result[i].col.length; j++) {
            if (result[i].col[j].SeatCode == '0000') {
              num++;
            }
          }
          if (num !== result[i].col.length) {
            //把这一列删除
            finalres.push(result[i])
          }
          num = 0;
        }

        for (var i = 0; i < finalres.length; i++) {
          finalres[i].row = i + 1;
        }

        result = finalres;
        var hangkuan = (column - mincol) + 1
        that.setData({
          // zuolist: zuolist,
          result,
          column: hangkuan
        })
        setTimeout(function () {
          // 放在最后--
          wx.hideLoading();
        }
          , 1200)
      })

    })




  },

  onShow: function () {
    payandshowprice = 0;
    this.setData({ hasclick: false, payandshowprice: 0 })
    cancou = false;
    wx.hideLoading();
    this.setData({
      result: [
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, ] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, ] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 6, ] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7, 9] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9, 7,] },
        { col: [1, 2, 3, 5, 6, 7, 8, , 8, 7, 9, 9,] },

      ]
    })
  },



  hasBuy: function () {
    wx.showModal({
      title: '提示',
      content: '该位置已经被购买，无法购买',
    })
  },
  /**选座事件**/
  gochkzuo: function (e) {

    if (e.currentTarget.dataset.pojo.StateSeat != 0) {
      return false;
    }

    // TODODODOD
    var currow = e.currentTarget.dataset.row
    var curcol = e.currentTarget.dataset.col
    console.log(currow - 1)
    console.log(curcol)
    //1.获取到 所选座位坐标
    //2.判断是否已经被选了如果是已经选了的 则修改状态为不选
    //选座部分

    for (var i = 0; i < result[currow - 1].col.length; i++) {
      if (result[currow - 1].col[i].SeatCol == curcol) {
        if (result[currow - 1].col[i].haschoose == true) {

          result[currow - 1].col[i].haschoose = false;
          for (var j = 0; j < hasChooseSeat.length; j++) {
            if (hasChooseSeat[j].SeatRow == currow && hasChooseSeat[j].SeatCol == curcol) {
              console.log('删除')
              hasChooseSeat.splice(j, 1)
              return req.CalculateActivityPrice(detail.EventDiscountTarget, detail.EventDiscountType, detail.EventDiscountValue, plandate.PriceService_wx, "1", plandate.PriceSale_wx, detail.EventDiscountThreshold).then(res => {

                payandshowprice = payandshowprice - parseInt(res.data.perpricetotal)

                console.log(payandshowprice)
                this.setData({ result, hasChooseSeat, totalprice, payandshowprice })
              })
            }
          }
        } else {
          if (hasChooseSeat.length >= detail.NumLimit) {
            wx.showModal({
              title: '提示',
              content: '最多只能选' + (parseInt(detail.NumLimit)) + "个座位",
              showCancel: false
            })
            return false;
          }

          result[currow - 1].col[i].haschoose = true; hasChooseSeat.push(result[currow - 1].col[i])
          //计算出以谁为中心
          console.log(currow)
          //x: currow * 30, y: curcol * 37.5,
          if (this.data.enlarge == 1) {
            var animation = wx.createAnimation({
              duration: 500,
              timingFunction: 'ease',
            })
            this.animation = animation

            animation.scale(2, 2).step().scale(1, 1).step();

            //导出动画
            this.setData({
              animationData: animation.export()
            })
          }


          this.setData({ scale: 1.5, hangscale: 1.5, hangnumTop: 0})

          console.log(curcol)
          return req.CalculateActivityPrice(detail.EventDiscountTarget, detail.EventDiscountType, detail.EventDiscountValue, plandate.PriceService_wx, "1", plandate.PriceSale_wx, detail.EventDiscountThreshold).then(res => {

            payandshowprice += parseInt(res.data.perpricetotal)

            this.setData({ result, hasChooseSeat, totalprice, payandshowprice })
          })
        }


      }
    }

    // })
    //计算出以谁为中心

    //   console.log("++++++++")


  },


  // htouchmove: function (e) { //初次手指触摸后移动为横向的移动
  //   console.log(e)
  // },

  // vtouchmove: function (e) { //初次手指触摸后移动为纵向的移动
  //   console.log(e)
  // },
  scrollTouchstart: function (e) {

    if (e.touches.length == 2) {//二指缩放
      if (!this.data.IsChoice) {
        return;
      }
      this.data.IsChoice = false;
      setTimeout(() => {
        this.data.IsChoice = true;
      }, 500);


      xMove = e.touches[1].clientX - e.touches[0].clientX
      yMove = e.touches[1].clientY - e.touches[0].clientY
      distance = Math.sqrt(xMove * xMove + yMove * yMove);//开根号

      if (flag == 0 || flag % 2 != 0) { //先滑动
        oldDistence = distance
      } else if (flag !== 0 && flag % 2 == 0) {
        newDistence = distance
      }
      flag = flag + 2;
      if (oldDistence !== '' && newDistence !== "") {
        distanceDiff = newDistence - oldDistence
      }


      if (distanceDiff > 0) {
        this.setData({ enlarge: 1 })
      } else {
        if (this.data.enlarge == 1) {
          var animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease',
          })
          this.animation = animation

          animation.scale(2, 2).step().scale(1, 1).step();

          //导出动画
          this.setData({
            animationData: animation.export()
          })
        }

        this.setData({  hangnumTop: 0 })
      }

    }
  },

  bindchange: function (e) {
    // console.log(e)
    this.setData({ hangscale: this.data.scale })
  },
  bindscale: function (e) {
    console.log(e)
    this.setData({ hangscale: e.detail.scale })
  },

  bindscroll: function (e) {
    console.log('滚动了', e)
    var s = 262 - e.detail.scrollLeft;
    this.setData({
      scrollLeft: e.detail.scrollLeft,
      moveLeft:s
    })

  },
 


  //确定去支付
  gopayfor: function (e) {
    LockCheck_rows = '';
    LockCheck_graphcels = '';
    var that = this;
    //判断是否选择座位 
    console.log(plandate)
    var chknum = hasChooseSeat.length;
    if (chknum == 0) {
      wx.showModal({
        title: '提示',
        content: '您没有选择座位！请选择',
      })
      return false;
    } else {
      //TOTO锁座
      wx.showLoading({
        title: '请稍候',
        mask: true
      })
      var PriceTotal = 0;
      var SeatInfo = "";
      for (var i = 0; i < hasChooseSeat.length; i++) {
        PriceTotal += (plandate.PriceSale_wx + plandate.PriceService_wx);
        if (hasChooseSeat.length > 1 && i < (hasChooseSeat.length - 1)) {
          SeatInfo += hasChooseSeat[i].SeatCode + "," + (plandate.PriceSale_wx + plandate.PriceService_wx) + "," + "0," + hasChooseSeat[i].Seattext + "|";
          LockCheck_rows = LockCheck_rows + hasChooseSeat[i].Seattext + ",";
          console.log(LockCheck_rows)
          console.log(hasChooseSeat[i].ScreenCol)
          LockCheck_graphcels = LockCheck_graphcels + hasChooseSeat[i].ScreenCol + ","
          console.log(LockCheck_graphcels)
        } else {
          SeatInfo += hasChooseSeat[i].SeatCode + "," + (plandate.PriceSale_wx + plandate.PriceService_wx) + "," + "0," + hasChooseSeat[i].Seattext;
          LockCheck_rows = LockCheck_rows + hasChooseSeat[i].Seattext;
          console.log(LockCheck_rows)
          console.log(hasChooseSeat[i].ScreenCol)
          LockCheck_graphcels = LockCheck_graphcels + hasChooseSeat[i].ScreenCol
          console.log(LockCheck_graphcels)
        }

      }


      //TODO锁座之前判断是否合格
      return req.LockCheck(LockCheck_rows, LockCheck_graphcels).then(res => {
        if (res.data.success) {
          // var OrderDetail = [];

          setTimeout(function () {
            // 放在最后--
            wx.hideLoading();
          }
            , 1600)

          return req.SaveLockEvent(Cinemapojo.AddTypeID, plandate.PlanCodeApp, PriceTotal, SeatInfo, UserID, app.globalData.loginuserinfo.mobile, EventId, hasChooseSeat.length, hasChooseSeat).then(res => {
            if (res.data.success) {
              order = res.data.data;
              console.log(order)
              cancou = true;
              wx.redirectTo({
                url: '../huodong/moviepayfor?paymoney=' + payandshowprice + '&&detail=' + JSON.stringify(detail) + '&&plandate=' + JSON.stringify(plandate) + '&&EventId=' + EventId + '&&order=' + JSON.stringify(order) + '&&chooseseat=' + JSON.stringify(hasChooseSeat) + '&&buyitem=' +buyitem+'',
              })
            } else {
              hasChooseSeat = [];
              this.setData({hasChooseSeat})
              setTimeout(function () {
                // 放在最后--
                wx.hideLoading();
              }
                , 1600)
              wx.showLoading({
                title: '锁座失败',
                success: function () {
                  payandshowprice = 0 ;
                  that.setData({ hasclick: false, payandshowprice })
                }
              })
              var getSeatMapSign = "strAppCode=" + strAppCode + "CinemaCode=" + Cinemapojo.CinemaCode + "PlanCodeApp=" + plandate.PlanCodeApp;
              return req.GetSignStr(getSeatMapSign).then(res => {
                if (res.data.success)
                  ReqGetSeatMapSign = res.data.data
              }).then(() => {
                return req.GetPlanSiteState(strAppCode, Cinemapojo.CinemaCode, plandate.PlanCodeApp, ReqGetSeatMapSign).then(res => {
                  var column = 0;
                  var row = 0;
                  var mincol = 0;
                  Seat = res.data.data;
                  mincol = Seat[0].ScreenCol;
                  for (let i = 0; i < Seat.length; i++) {
                    if (i == Seat.length - 1) {
                      column = Seat[i].ScreenCol
                      row = Seat[i].ScreenRow
                    }
                  }
                  console.log(Seat)
                  result = zuodata.getXiSeat(column, row, Seat);

                  //TODO 过滤空行
                  var num = 0;
                  var finalres = [];
                  for (var i = 0; i < result.length; i++) {
                    for (var j = 0; j < result[i].col.length; j++) {
                      if (result[i].col[j].SeatCode == '0000') {
                        num++;
                      }
                    }
                    if (num !== result[i].col.length) {
                      //把这一列删除
                      finalres.push(result[i])
                    }
                    num = 0;
                  }

                  for (var i = 0; i < finalres.length; i++) {
                    finalres[i].row = i + 1;
                  }

                  result = finalres;
                  var hangkuan = (column - mincol) + 1
                  that.setData({
                    // zuolist: zuolist,
                    result,
                    column: hangkuan
                  })
                  setTimeout(function () {
                    // 放在最后--
                    wx.hideLoading();
                  }
                    , 1200)
                })
              })

            }

          }).then(() => {
            if (cancou) {
              // 显示遮罩层
              var animation = wx.createAnimation({
                duration: 100,
                timingFunction: "ease-in-out",
                delay: 0
              })

              that.animation = animation
              animation.translateY(300).step();

              that.setData({
                animationData: animation.export(),
                showmodel: true,//显示弹出层
              })
              setTimeout(function () {
                animation.translateY(0).step()
                that.setData({
                  animationData: animation.export()
                })
              }.bind(that));
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
          })
          wx.hideLoading();
        }
      })

      // })

    }
  },
  /**点击关闭按钮***/
  hidemodal: function () {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showmodel: false,//隐藏弹出层
      })

    }.bind(this), 200)
  },
  //我知道了，跳转到支付页面
  goconfirm: function () {
    var that = this;
    that.hidemodal();
    wx.redirectTo({
      url: '../huodong/moviepayfor?paymoney=' + payandshowprice + '&&detail=' + JSON.stringify(detail) + '&&plandate=' + plandate + '&&EventId=' + EventId + '',
    })
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

    var that = this;
    that.setData({
      showbottom: true
    })
  },
})

Array.prototype.remove = function (obj) {
  for (var i = 0; i < this.length; i++) {
    var temp = this[i];
    if (!isNaN(obj)) {
      temp = i;
    }
    if (temp == obj) {
      for (var j = i; j < this.length; j++) {
        this[j] = this[j + 1];
      }
      this.length = this.length - 1;
    }
  }
} 
